import axios, { AxiosInstance, AxiosProxyConfig } from 'axios'
import {isNull, eachProp} from '@/utils/Common'

// ts写法
// const service: AxiosInstance= axios.create({
//     baseURL: '/',
//     timeout: 3000
// })

const service = axios.create({
    baseURL: '/',
    timeout: 3000
})

// get 请求,将data 包装到url上
function wrapParamUrl(originUrl, data){
    let url = `${originUrl}?`;
    if(data) {
        eachProp(data, prop => {
            if(!isNull(data[prop])) {
                url += `${prop}=${data[prop].toString()}&`
            }
        })
    }
    // S删除url中最后一个&
    url = url.substring(0, url.length - 1)
    return url;
}

// request 拦截器
// ts写法
// service.interceptors.request.use((originConfig: AxiosProxyConfig) => {
service.interceptors.request.use(originConfig => {
    const config = originConfig;
    const method = String(config.method).toUpperCase();
    if(method === 'POST'){

    } else if (method === 'GET') {
        config.url = wrapParamUrl(config.url, config.data)
    }
    return config
}, err => Promise.reject(err))

// response 拦截器
service.interceptors.response.use(response => {
    console.log(response);
    return response;
}, err => Promise.reject(err))

export default service;
